<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label=" 机构  "  prop="departmentId">
          <el-select v-model="listQuery.departmentId" @change="deptChange" clearable placeholder="请选择">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="停车场">
          <el-select clearable v-model="listQuery.parkId" placeholder="请选择">
            <el-option
              v-for="item in allParkList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="车牌号码">
          <el-input clearable v-model="listQuery.plateNumber" clearable class="filter-item" style="width: 180px;" placeholder="请输入"/>
        </el-form-item>

        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>

        <el-button
          v-hasPermi="['admin:ownerCar:create']"
          class="filter-item"
          style="float:right"
          type="primary"
          icon="el-icon-plus"
          @click="startAdd">添加</el-button>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row >
      <el-table-column align="center" label="机构名称" prop="departmentName" />
      <el-table-column align="center" label="车主名称" prop="name"/>

      <el-table-column align="center" label="停车场" prop="parkName"/>

      <el-table-column align="center" label="电话号码" prop="phoneNumber"/>

      <el-table-column align="center" label="房屋号码" prop="houseNumber"/>

      <el-table-column align="center" label="车位号码" prop="parkingSpaceNumber"/>

      <el-table-column align="center" label="车牌号码1" prop="plateNumber1"/>

      <el-table-column align="center" label="车牌号码2" prop="plateNumber2"/>

      <el-table-column align="center" label="车位类型描述" prop="parkingSpaceTypeStr" show-overflow-tooltip/>

      <!-- <el-table-column align="center" label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag >{{ getStatus(scope.row.status) }}</el-tag>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="操作" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['admin:ownerCar:update']"
            type="primary"
            size="small"
            @click="startEditBlacklistCar(scope.row)">编辑</el-button>
          <el-button
            v-hasPermi="['admin:ownerCar:delete']"
            type="primary"
            size="small"
            @click="deleteBlacklistCar(scope.row.name, scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="dialogType == 1?'添加业主车辆':'修改业主车辆'" :visible.sync="dialogFormVisible" width="1000px">
      <el-form ref="dialogForm"  :rules="formRules" :model="dialogForm" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label=" 机构  " prop="departmentId">
              <el-select :disabled="dialogType == 2" style="width: 100%;" v-model="dialogForm.departmentId" placeholder="请选择" @change="departmentChange">
                <el-option
                  v-for="item in departmentList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 停车场  " prop="parkId">
              <el-select :disabled="dialogType == 2" style="width: 100%;" v-model="dialogForm.parkId" placeholder="请选择">
                <el-option
                  v-for="item in parkList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 车主姓名  " prop="name">
              <el-input style="width: 100%;" v-model="dialogForm.name" clearable class="filter-item"  placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 房号地址  " prop="houseNumber">
              <el-input style="width: 100%;" v-model="dialogForm.houseNumber" clearable class="filter-item" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 车主电话  " prop="phoneNumber">
              <el-input style="width: 100%;" v-model="dialogForm.phoneNumber" clearable class="filter-item"  placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 车位号  " prop="parkingSpaceNumber">
              <el-input style="width: 100%;" v-model="dialogForm.parkingSpaceNumber" clearable class="filter-item"  placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 车位类型  " prop="parkingSpaceType">
              <el-select style="width: 100%;" v-model="dialogForm.parkingSpaceType" placeholder="请选择">
                <el-option
                  v-for="item in cheweiType"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 车牌号1  " prop="plateNumber1">
              <el-input style="width: 100%;" v-model="dialogForm.plateNumber1" clearable class="filter-item"  placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 车牌号2  " prop="plateNumber2">
              <el-input style="width: 100%;" v-model="dialogForm.plateNumber2" clearable class="filter-item"  placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过期是否收费 " prop="expiryFeeFlag">
              <el-radio-group v-model="dialogForm.expiryFeeFlag">
                <el-radio
                v-for="item in dict.type.EYesOrNo"
                :key="item.value"
                :label="Number(item.value)">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 有效期  " prop="endTime">
              <!-- <el-date-picker
                :picker-options="pickerOptions"
               style="width: 100%;"
                v-model="dialogForm.dateRange"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间">
              </el-date-picker> -->
              <el-date-picker
                :picker-options="pickerOptions"
                value-format="yyyy-MM-dd HH:mm:ss"
                v-model="dialogForm.endTime"
                type="datetime"
                default-time="00:00:00"
                placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="confirmEdit('dialogForm')">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
/* eslint-disable eqeqeq */

import { fetchList, deleteOwnerCar, createOwnerCar, updateOwnerCar,ownerCarDetail } from '@/api/business/ownerCar'
import { getDepartmentList,getListAuthPark } from '@/api/base'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { YyMmDdToTimes,timesToYyMmDd1 } from '@/utils/time'
import { getData, } from '@/api/system/dictionary'
export default {
  name: 'OwnerCar',
  dicts: ['EYesOrNo',],
  components: { Pagination },
  data() {
    return {
      pickerOptions: {
          disabledDate(time) {
              return time.getTime() < Date.now() - 8.64e7;
          }
      },
      cheweiType:[],//车位类型数据
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20
      },
      downloadLoading: false,
      dialogFormVisible: false,
      dialogForm: {},
      dialogType: 1,
      departmentList: [],
      parkList: [],
      allParkList: [],
      passwayList: [],
      qrcodeDialogVisible: false,
      formRules: {
        parkId: [{ required: true, message: '请选择停车场', validator: this.checkSelected, trigger: 'change' }],
        name: [{ required: true, message: '请输入车主姓名', trigger: 'blur' }],
        departmentId: [{ required: true, message: '请选择机构名称', validator: this.checkSelected, trigger: 'change' }],
        houseNumber: [{ required: true, message: '请输入房号地址', trigger: 'blur' }],
        phoneNumber: [
          { required: true, message: '请输入车主电话', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的车主电话号码",
            trigger: "blur"
          }
        ],
        parkingSpaceNumber: [{ required: true, message: '请输入车位号码', trigger: 'blur' }],
        parkingSpaceType: [{ required: true, message: '请选择车位类型', validator: this.checkSelected, trigger: 'change' }],
        plateNumber1: [{ required: true, message: '请输入车牌号1', trigger: 'blur' }],
        endTime: [{ required: true, message: '请选择有效期', trigger: 'blur' }],
        expiryFeeFlag: [{ required: true, message: '请选择过期是否收费', trigger: 'change' }],
      }
    }
  },
  created() {
     this.getDepartmentList()
     this.getList()
		this.getData()
  },
  methods: {
    getDepartmentList(){//获取机构
      getDepartmentList().then(res => {
        this.departmentList = res.data || []
      })
    },
    async getListAuthPark(departmentId){//获取停车场
      let res = await getListAuthPark({departmentId})
      return res.data || []
    },
		async getData(){//车位类型
			let res = await getData('EParkingSpaceType')
			let list = res.data || []
			this.cheweiType = [...list]
		},
    async deptChange(e){//机构下拉选择
      let listQuery = {...this.listQuery}
      listQuery.parkId = ''
      this.listQuery = {...listQuery}
      if(!e) return this.allParkList = []
      this.allParkList = await this.getListAuthPark(e)
    },
    // 校验下拉框
    checkSelected(rule, value, callback) {
      if (!value) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        let data = response.data || {}
        this.list = data.list || []
        this.total = data.total || 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    getStatus(status) {
      if (status === '1') {
        return '启用'
      }
      return '停用'
    },
    deleteBlacklistCar(name, parkId) {
      this.$confirm(`您确定删除该业主车辆`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOwnerCar(parkId).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          this.getList()
        })
      })
    },
    startAdd() {
      this.dialogFormVisible = true
      this.parkList = []
      this.$nextTick(()=>{
        this.dialogForm = {expiryFeeFlag:0}
        this.$refs['dialogForm'].resetFields();
        this.dialogType = 1
      })
      this.getDepartmentList()
    },
    confirmEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let dialogForm = {...this.dialogForm}
          // dialogForm.startTime = dialogForm.dateRange[0]
          // dialogForm.endTime = dialogForm.dateRange[1]
          delete dialogForm.dateRange
          if (this.dialogType == 1) {
            createOwnerCar(dialogForm).then(response => {
              this.$message({
                message: '添加成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          } else {
            updateOwnerCar(dialogForm).then(response => {
              this.$message({
                message: '修改成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    startEditBlacklistCar(row) {
      this.dialogFormVisible = true
      this.$nextTick(async ()=>{
        this.dialogForm = {}
        this.$refs['dialogForm'].resetFields();
        this.dialogType = 2
        let res = await ownerCarDetail(row.id)
        let data = res.data || {}
        let dialogForm = {
          ...data,
          expiryFeeFlag:data.expiryFeeFlag || 0
        }

        dialogForm.dateRange = [dialogForm.startTime,dialogForm.endTime]
        this.dialogForm = {...dialogForm}
        this.parkList = []
        this.parkList = await this.getListAuthPark(this.dialogForm.departmentId)
        this.getDepartmentList()
      })

    },
    departmentChange(e){//部门下拉改变
      let dialogForm = {...this.dialogForm}
      dialogForm.parkId = ''
      this.dialogForm = {...dialogForm}
      this.selectDepartmentId(e)
    },
    async selectDepartmentId(event) {
      this.parkList = []
      this.parkList = await this.getListAuthPark(event)
    }

  }
}
</script>
